package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.service.TransportApiApplyThirdpartyManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.TransportApiApplyThirdpartyDTO;
import com.hunttown.mes.rpc.domain.query.TransportApiApplyThirdpartyDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2022-04-10 09:47:59
 */
@Controller
@RequestMapping(value = "/basic/api-thirdparty")
public class ApiApplyThirdpartyController {

    private final static Logger logger = LoggerFactory.getLogger(ApiApplyThirdpartyController.class);

    private final TransportApiApplyThirdpartyManageService transportApiApplyThirdpartyService;
    private final AnalysisManageManageService manageService;

    @Autowired
    public ApiApplyThirdpartyController(TransportApiApplyThirdpartyManageService transportApiApplyThirdpartyService, AnalysisManageManageService manageService) {
        this.transportApiApplyThirdpartyService = transportApiApplyThirdpartyService;
        this.manageService = manageService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, TransportApiApplyThirdpartyDTOQuery dtoQuery) {

        dtoQuery.setOrderBy("order by id desc");
        Page<TransportApiApplyThirdpartyDTO> dataPage = transportApiApplyThirdpartyService.getForPage(dtoQuery);
        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "basic/api-thirdparty/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        TransportApiApplyThirdpartyDTO obj;

        if (id > 0) {
            obj = transportApiApplyThirdpartyService.getById(id);
        } else {
            obj = new TransportApiApplyThirdpartyDTO();
            obj.setId(0);
            obj.setEffectiveTime(0);
        }
        model.addAttribute("Obj", obj);

        return "basic/api-thirdparty/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportApiApplyThirdpartyDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                TransportApiApplyThirdpartyDTOQuery query = new TransportApiApplyThirdpartyDTOQuery();
                query.setAppId(objDTO.getAppId());
                TransportApiApplyThirdpartyDTO obj = transportApiApplyThirdpartyService.getByQuery(query);

                if (obj != null && obj.getId() > 0) {
                    //说明此记录已经存在，不能重复插入
                    map = OperateCode.CompositionResult(map, -10, "此APPID已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = transportApiApplyThirdpartyService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = transportApiApplyThirdpartyService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = transportApiApplyThirdpartyService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = transportApiApplyThirdpartyService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        TransportApiApplyThirdpartyDTO obj = new TransportApiApplyThirdpartyDTO();
        obj.setId(id);

        if (id > 0) {
            obj = transportApiApplyThirdpartyService.getById(id);
        }
        transportApiApplyThirdpartyService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

}